

function renderTemplate(name, context) {
  getTemplate(name, function (tpl) {
    var container = document.getElementById("content");
    container.innerHTML = "";
    container.appendChild(tpl);
    
    if (context == null) {
      context = new JsEvalContext({});
    }
    
    jstProcess(context, container);

  });
}

/**
 * Returns a copy of the template to the given callback function
 * @param name The template name
 * @param callback
 */
function getTemplate(name, callback) {
  var root = jstGetTemplate(name); 
  if (root) {
    callback(root);
  } else {
    loadTemplate(name, function(content) {
      var box = document.createElement("div");
      box.innerHTML = content;
      var tpls = document.getElementById("templates");
      tpls.appendChild(box);
      
      resolveTransclusions(tpls, function() {
        var original = document.getElementById(name);
        preprocessTemplate(original);
        root = jstGetTemplate(name);
        callback(root);
      });
    });
  }
}

function resolveTransclusions(element, callback) {
  var children = element.getElementsByTagName('*');
  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    var transclude = child.getAttribute("transclude");
    if (transclude && !document.getElementById(transclude)) {
      getTemplate(transclude, function() {
        resolveTransclusions(element, callback);
      });
      return;
    }
  }
  callback();
}


function loadTemplate(name, callback) {
  var query = {"type": "/template", "name": name, "content": null};
  mqlRead(query, function(result) {
    callback(result["content"]);
  })
}

function preprocessJsquery(element, jsquery) {
  var cut = jsquery.indexOf(':');
  var varName = jsquery.substring(0, cut);
  var vars = {};
  vars[varName] = jsquery.substring(cut+1).trim().indexOf("[") == 0 ? [{}] : {};
  
  collectQuery(element, vars);
  console.log("enriched vars: " + JSON.stringify(vars));
  element.setAttribute("enriched_query", JSON.stringify(vars[varName]));
}

function preprocessTemplate(element) {
  var jsquery = element.getAttribute("jsquery");
  if (jsquery) {
    preprocessJsquery(element, jsquery);
  }
  for(var child = element.firstElementChild; child != null; child = child.nextElementSibling) {
    preprocessTemplate(child);
  }
}
